package com.jf.car.service.impl;

import com.jf.car.bean.Car;
import com.jf.car.bean.Category;
import com.jf.car.dao.CarDao;
import com.jf.car.dao.CategoryDao;
import com.jf.car.dao.impl.CarDaoImpl;
import com.jf.car.dao.impl.CategoryDaoImpl;
import com.jf.car.service.CategoryService;
import com.jf.car.util.MyConstants;
import com.jf.car.util.PageInfo;
import com.jf.car.util.ResultJson;

import java.util.Collections;
import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    private CategoryDao categoryDao = new CategoryDaoImpl();
    private CarDao carDao = new CarDaoImpl();

    @Override
    public List<Category> getAll() {
        return categoryDao.getAll();
    }

    @Override
    public ResultJson getSelect() {
        return ResultJson.success(categoryDao.getAll());
    }

    @Override
    public ResultJson getPage(PageInfo pageInfo, Category category) {
        List<Category> list = categoryDao.getPage(pageInfo, category);
        int count = categoryDao.getCount(category);
        pageInfo.setPageData(list, count);
        return ResultJson.success(pageInfo);
    }

    @Override
    public ResultJson saveOrUpdate(Category category) {
        int result;
        if (category.getId() == null) {
            Category searchInfo = categoryDao.getByName(category.getName());
            if (searchInfo == null) {
                category.setStatus(MyConstants.STATUS_1);
                result = categoryDao.addSelect(category);
            } else {
                return ResultJson.error("分类名称已存在！");
            }
        } else {
            result = categoryDao.upateSelect(category);
        }
        return result > 0 ? ResultJson.success() : ResultJson.error("操作失败");
    }

    @Override
    public ResultJson delete(int id) {
        List<Car> list = carDao.getCarByCategoryId(id);
        if (!list.isEmpty()) {
            return ResultJson.error("编号【" + list.get(0).getCategoryId() + "】已被使用，无法删除");
        }
        int result = categoryDao.delete(id);
        return result > 0 ? ResultJson.success() : ResultJson.error("删除失败！");
    }

    @Override
    public ResultJson info(int id) {
        return ResultJson.success(categoryDao.getById(id));
    }
}
